﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using com.woodsoft.core;
using EQ1.Elements;
using System.Xml;
using com.woodsoft.core.Files;
using EQ1.Objects;

namespace EQ1.Controls {
  public class TemplateContainer : Control , IUIElement<TemplateContainer> {
    public TemplateContainer ( UIDocument doc , string name )
      : base( doc , name ) {
    }
    public TemplateContainer ( UIDocument doc )
      : this( doc , "TemplateContainer" ) {
    }

    #region IUIElement<TemplateContainer> Members

    public void Validate ( TemplateContainer val , string name ) {
      UIClass par = ( UIClass ) this.ParentNode;

      if( val.LocalName != name ) {
        TemplateContainer el = new TemplateContainer( ( UIDocument ) val.OwnerDocument , name );
        el.Copy( val );
        val = el;
      }

      if( par.GetElement( name ) != null )
        par.RemoveElement( name );

      par.AppendChild( val );
    }

    public void Copy ( TemplateContainer val ) {
      base.Copy( val );

      if( val.TemplatePieces != null )
        this.TemplatePieces = val.TemplatePieces;
      if( val.Pieces != null )
        this.Pieces = val.Pieces;
    }

    #endregion
    //Collection of NamedTemplatePiece pieces
    public XmlNodeList TemplatePieces {
      get {
        return this.GetElementsByTagName( "TemplatePieces" );
      }
      set {
        foreach( NamedTemplatePiece nd in value ) {
          if( nd.LocalName == "TemplatePieces" )
            this.AddTemplatePiece( nd );
        }
      }
    }
    public void AddTemplatePiece ( NamedTemplatePiece val ) {
      if( val.LocalName == "TemplatePieces" ) {
        for( int i = this.TemplatePieces.Count - 1 ; i >= 0 ; i-- ) {
          if( val.item == ( ( NamedTemplatePiece ) this.TemplatePieces[i] ).item ) {
            this.ReplaceChild( val , this.TemplatePieces[i] );
            return;
          }
        }

        this.AppendChild( val );
      }
    }
    public NamedTemplatePiece GetTemplatePiece ( string item ) {
      foreach( NamedTemplatePiece nd in this.TemplatePieces ) {
        if( nd.item == item )
          return nd;
      }

      return null;
    }

    //Collection of ScreenPiece:item values
    public XmlNodeList Pieces {
      get {
        return this.GetElementsByTagName( "Pieces" );
      }
      set {
        foreach( XmlNode nd in value ) {
          if( nd.LocalName == "Pieces" )
            this.AddPiece( nd.InnerText );
        }
      }
    }
    public void AddPiece ( string val ) {
      for( int i = this.Pieces.Count - 1 ; i >= 0 ; i-- ) {
        if( this.Pieces[i].InnerText == val )
          return;
      }

      this.AddElement( "Pieces" , val );
    }
  }
}
